<?php

namespace app\admin\controller\vip;

use app\common\controller\Backend;
use think\Db;

/**
 * 
 *
 * @icon fa fa-circle-o
 */
class User extends Backend
{
    
    /**
     * User模型对象
     * @var \app\admin\model\vip\User
     */
    protected $model = null;

    public function _initialize()
    {
        parent::_initialize();
        $this->model = new \app\admin\model\vip\User;

    }
    
    /**
     * 默认生成的控制器所继承的父类中有index/add/edit/del/multi五个基础方法、destroy/restore/recyclebin三个回收站方法
     * 因此在当前控制器中可不用编写增删改查的代码,除非需要自己控制这部分逻辑
     * 需要将application/admin/library/traits/Backend.php中对应的方法复制到当前控制器,然后进行修改
     */


    /**
     * 查看
     */
    public function index()
    {
        //设置过滤方法
        $this->request->filter(['strip_tags']);
        if ($this->request->isAjax()) {
            //如果发送的来源是Selectpage，则转发到Selectpage
            if ($this->request->request('keyField')) {
                return $this->selectpage();
            }
            list($where, $sort, $order, $offset, $limit) = $this->buildparams();
            $total = $this->model
                ->where($where)
                ->order($sort, $order)
                ->count();

            $list = $this->model
                ->where($where)
                ->order($sort, $order)
                ->limit($offset, $limit)
                ->select();

            $list = collection($list)->toArray();
            // 查询总金额
            $money = $this->model->where($where)->sum("money");
            $result = array("total" => $total, "rows" => $list,"extend" => ['money' => $money]);

            return json($result);
        }
        return $this->view->fetch();
    }



    public function orderlist()
    {
        $data = Db::name("user")->alias("a")
            ->field("a.id,a.username,a.level,d.savemoney,b.money AS sj_money,c.money AS hyj_money,d.money AS cm_money")
            ->join("vip_jiangli b","a.username = b.username","LEFT")
            ->join("vip_haoyun c","a.username = c.username","LEFT")
            ->join("vip_chouma d","a.username = d.username","LEFT")
            ->where("(b.money > 0 || c.money > 0 || d.money > 0)")
            ->select();
    }


    /**
     * 批量修改状态
     */
    public function send_status()
    {
        if($this->request->isAjax()){
            Db::name("vip_jiangli")->where("status",0)->update(["status"=>1]);// 晋级奖励
            Db::name("vip_haoyun")->where("status",0)->update(["status"=>1]);// 每月好运金
            Db::name("vip_chouma")->where("status",0)->update(["status"=>1]);// 每月筹码
            return json(['status'=>200,"msg"=>"操作成功"]);
        } else {
            return json(['status'=>400,"msg"=>"请求类型错误"]);
        }
    }


    /**
     * 升级派彩
     */
    public function payout()
    {
        ini_set("memory_limit","800M");
        set_time_limit(0);
        if($this->request->isPost()){
            $re = ["status"=>401,"msg"=>"选项错误"];
            $type = input("type");
            $month = input("type_time") ? input("type_time") : date("Y-m");
            // 升级
            if($type == 3){ // 每月好运金
                $re = $this->save_haoyun($month);
            }
            if($re["status"] == 200){
                $this->success($re['msg']);
            } else {
                $this->error($re['msg']);
            }
        }
        return $this->view->fetch();
    }


    // ==============================================================


    /**
     * 保存好运金
     */
    public function save_haoyun($month)
    {
        // 查询这个月有投注的用户【以您上个月18日至本月17日期间的有效投注计算，可得相对应的好运金】
        $time = time();
        $m = date("m",strtotime($month)) - 1;
        $m2 = $m+1;
        $startTime = strtotime(date("Y-".$m."-18"));
        $endTime = strtotime(date("Y-".$m2."-18"));
        //dump($startTime);
        //dump($endTime);
        //$month = date("Y-m",$time);
        //$startTime= strtotime(date("Y-m-1",$time));
        //$endTime = strtotime(date('Y-m-1',strtotime('next month')));
        $order_count = Db::name("vip_orders")->where("savetime >= $startTime && savetime < $endTime")->where("status != 1")->count();
        if($order_count > 0){
            return ["status"=>400,"msg"=>"请过段时间派彩，系统正在归档数据"];
        }
        $data = Db::name("vip_orders")->alias("a")
            ->join("vip_user b","a.username = b.username")
            ->field("a.*,SUM(a.money) AS month_money,b.level")
            //->where("a.savetime >= $startTime AND a.savetime < $endTime")
            ->where("a.savetime >= $startTime && a.savetime < $endTime")
            ->where("a.status",1)
            ->where("b.level > 0")
            ->group("a.username")
            ->select();
        //dump(Db::name("vip_orders")->getLastSql());
        //dump($data);die;
        if(empty($data)){
            return ["status"=>200,"msg"=>"已派彩成功"];
        }
        $caijinData = Db::name("vip_caijin")->order("save_money desc")->cache(true)->select();//奖金
        foreach($data as $k=>$v) {
            $haoyunMoney = $this->haoyun_money($v["level"],$v["month_money"],$caijinData);
            if($haoyunMoney > 0) {
                $choumaData["username"] = $v["username"];
                $choumaData["savemoney"] = $v["month_money"];
                $choumaData["money"] = $haoyunMoney;
                $choumaData["savetime"] = $month;
                $choumaData["status"] = 0;
                $user = Db::name("vip_haoyun")->where("username",$v["username"])->where("savetime",$month)->find();
                if(!empty($user)){
                    Db::name("vip_haoyun")->where("id",$user["id"])->update($choumaData);
                } else {
                    Db::name("vip_haoyun")->insert($choumaData);
                }
            }
        }
        return ["status"=>200,"msg"=>"派彩成功"];
    }
    /**
     * 查询当前彩金对应奖励
     */
    public function haoyun_money($level,$save_money,$caijinData)
    {
        $money = 0;
        foreach($caijinData as $v){
            if($save_money >= $v["save_money"] && $level >= $v["level_start"]){
                $money = $v["money"];
                break;
            }
        }
        return $money;
    }


    //=========================================================


}
